package cn.b.sky.common.file;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class GridModel implements ExcelModel {

  private static final Logger log = LoggerFactory.getLogger(GridModel.class);

  // 表头映射
  private List<Map> columnMaps;

  // 数据列表
  private List<Map<String, Object>> dataList;

  private Excel excel;

  public GridModel(List<Map> columnMaps, List<Map<String, Object>> dataList) {
    this.columnMaps = columnMaps;
    this.dataList = dataList;
  }

  /**
   * @return columnMaps
   */
  public List<Map> getColumnMaps() {
    return columnMaps;
  }

  /**
   * @param columnMaps
   *            要设置的 columnMaps
   */
  public void setColumnMaps(List<Map> columnMaps) {
    this.columnMaps = columnMaps;
  }

  /**
   * @return dataList
   */
  public List<Map<String, Object>> getDataList() {
    return dataList;
  }

  /**
   * @param dataList
   *            要设置的 dataList
   */
  public void setDataList(List<Map<String, Object>> dataList) {
    this.dataList = dataList;
  }

  @Override
  public String type() {
    return ExcelUtil.GRID;
  }

  @Override
  public void setExcel(Excel excel) {
    this.excel = excel;
  }

  @Override
  public Point insert(Point start) {

    HSSFWorkbook workBook = excel.getWorkwork();
    HSSFSheet sheet = excel.getSheet();
    CellStyle cs = workBook.createCellStyle();
    cs.setAlignment((short) 0x2);

    List<String> fields = new ArrayList<String>();

    int colIndex = start.getCol();
    int rowNumber = start.getRow();
    Row row = sheet.createRow(rowNumber);
    // 表头
    if (columnMaps != null) {
      for (Map<String, Object> map : columnMaps) {
        Cell cell = row.createCell(colIndex);
        cell.setCellValue(map.get(ExcelUtil.COLUMN_TEXT).toString());
        String ss = map.get(ExcelUtil.COLUMN_WIDTH).toString();
        sheet.setColumnWidth(colIndex, ExcelUtil.COLUMN_WIDTH_FACTOR * Float.valueOf(ss).intValue());
        fields.add(map.get(ExcelUtil.COLUMN_NAME).toString());
        colIndex++;
      }
    }

    // 表内容
    if (dataList != null) {
      for (Map<String, Object> model : dataList) {
        row = sheet.createRow(++rowNumber);

        for (int i = 0; i < fields.size(); i++) {
          Cell cell = row.createCell(start.getCol() + i);
          Object value = model.get(fields.get(i).toUpperCase());
          try {
            ExcelUtil.setCellValue(cell, value);
          } catch (Exception e) {
            log.error("{}", e);
          }
        }
      }
    }
    return new Point(start.getCol() + fields.size(), row.getRowNum());

  }

}
